package com.shinemo.mpush.alloc.handler;

import java.io.IOException;
import java.util.Map;

import com.mpush.api.chat.MemberNotification;
import com.mpush.api.chat.MemberNotificationReceiver;
import com.shinemo.mpush.alloc.vo.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mpush.api.chat.ChatSession;
import com.mpush.api.chat.ChatSessionNotification;
import com.mpush.api.protocol.PushType;
import com.mpush.api.push.MsgType;
import com.mpush.api.push.PushContent;
import com.mpush.api.push.PushContext;
import com.mpush.api.push.PushMsg;
import com.mpush.api.push.PushSender;
import com.mpush.netty.http.HttpClient;
import com.mpush.tools.Jsons;
import com.shinemo.mpush.alloc.common.ResultCode;
import com.shinemo.mpush.alloc.http.HttpRequest;
import com.shinemo.mpush.alloc.http.HttpResponse;
import com.shinemo.mpush.alloc.service.MesIdService;
import com.shinemo.mpush.alloc.service.SessionService;
import com.shinemo.mpush.alloc.vo.ChatSessionResponse;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class MemberHandler implements HttpHandler{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private PushSender pushSender = null;
	private HttpClient httpClient = null;
	private MesIdService mesIdService=null;
	

	public MemberHandler(PushSender pushSender, HttpClient httpClient, MesIdService mesIdService) {
		this.pushSender=pushSender;
		this.httpClient=httpClient;
		this.mesIdService=mesIdService;
	}

	@Override
	public void handle(HttpExchange httpExchange) throws IOException {



		BaseResponse response=new ChatSessionResponse();


		try {
			String body = HttpRequest.getBody(httpExchange);
			logger.info("接收到的消息:{}", body);
			Map<String, Object> params=HttpRequest.toMap(body);

			response = this.sendPush(params);
		}
		catch(Exception e) {
			logger.error("",e);
			response.setCode(ResultCode.INTERNAL_SERVER_ERROR.getCode());
			response.setMes("内部错误");
		}
		
		HttpResponse.writeJson(httpExchange, Jsons.toJson(response));
	}
	
	private BaseResponse sendPush(Map<String, Object> params) {

		MemberNotification memberNotification = Jsons.fromJson(Jsons.toJson(params), MemberNotification.class);
		MemberNotificationReceiver memberNotificationReceiver = Jsons.fromJson(Jsons.toJson(params), MemberNotificationReceiver.class);
		
		PushContent pushContent=new PushContent(PushType.CHAT_MEMBER_CHANGE,Jsons.toJson(memberNotification));
		
		PushMsg pushMsg = PushMsg.build(MsgType.NOTIFICATION_AND_MESSAGE, Jsons.toJson(pushContent));
		pushMsg.setMsgId(mesIdService.createMesId());

		pushSender.send(PushContext.build(pushMsg).setUserId(memberNotificationReceiver.getReceiverId()));

		BaseResponse response=new BaseResponse();
		response.setCode(ResultCode.SUCCESS.getCode());
		response.setMes("成功");
		return response;
	}
	
}
